package com.shu.logsearch.util;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.Closeable;
import java.io.IOException;

/**
 * 用于关闭各种连接的工具类
 *
 * @author Tree Cai
 * @date 2019/7/2
 */
public class CloseUtil {

    private static Logger logger = LoggerFactory.getLogger(CloseUtil.class);

    /**
     * 关闭连接
     *
     * @param channel
     * @param name
     */
    public static void disConnect(Channel channel, String name) {
        if (channel != null) {
            if (channel.isConnected()) {
                channel.disconnect();
                channel = null;
                info(channel, name);
            }
        }
    }

    /**
     * 关闭连接
     *
     * @param session
     * @param name
     */
    public static void disConnect(Session session, String name) {
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
                session = null;
                info(session, name);
            }
        }
    }

    /**
     * 关闭连接
     *
     * @param closeable
     * @param name
     */
    public static void close(Closeable closeable, String name, Boolean info) {
        if (closeable != null) {
            try {
                closeable.close();
                if (info)
                    info(closeable, name);
            } catch (IOException e) {
                error(closeable, name);
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭连接
     *
     * @param closeable
     * @param name
     */
    public static void close(Closeable closeable, String name) {
        close(closeable, name, true);
    }

    /**
     * 关闭连接
     *
     * @param closeable
     */
    public static void close(Closeable closeable) {
        close(closeable, null, false);
    }

    /**
     * 提示日志
     *
     * @param object
     * @param name
     */
    private static void info(Object object, String name) {
        if (StringUtils.isEmpty(name))
            name = object.getClass().getName();
        logger.info(name + " 连接已关闭");
    }

    /**
     * 错误日志
     *
     * @param object
     * @param name
     */
    private static void error(Object object, String name) {
        if (StringUtils.isEmpty(name))
            name = object.getClass().getName();
        logger.error(name + " 关闭连接出错");
    }
}
